package whu.cn.whushare.ui.main.known;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.android.volley.VolleyError;
import com.androidplus.util.ViewMapping;
import com.androidplus.util.ViewMappingUtil;
import com.dd.processbutton.iml.ActionProcessButton;

import whu.cn.whushare.R;
import whu.cn.whushare.bean.Result;
import whu.cn.whushare.common.Constants;
import whu.cn.whushare.net.DownloadParams;
import whu.cn.whushare.net.Downloader;
import whu.cn.whushare.ui.common.BaseActivity;
import whu.cn.whushare.util.SetOnClickUtil;

@ViewMapping(id = R.layout.activity_add_answer)         //获取添加问题回答的布局文件
public class AddAnswerActivity extends BaseActivity {
	@ViewMapping(id = R.id.publish_answer)              //获取发布按钮
	private ActionProcessButton mPublishAnswerBtn;
	@ViewMapping(id = R.id.content)                     //获取回答内容编辑框
	private EditText mContentEdit;

	private String mQuestionId;

    //获取跳转到当前activity的intent信息，向intent中添加问题id
	public static Intent getStartIntent(Context context, String questionId) {
		Intent i = new Intent(context, AddAnswerActivity.class);
		i.putExtra(Constants.INTENT_EXTRA_QUESTION_ID, questionId);
		return i;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewMappingUtil.mapView(this, this);
        //为当前类注册点击事件监听器
		SetOnClickUtil.registerOnClick(this);
		mQuestionId = getIntent().getStringExtra(Constants.INTENT_EXTRA_QUESTION_ID);
	}

	@Override
    //定义点击事件响应函数
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
		case R.id.publish_answer:
			String content = mContentEdit.getText().toString();
			if (TextUtils.isEmpty(content)) {
				toast(R.string.no_answer_content);
			} else {
				publishAnswer(content);
			}
			break;
		default:
			break;
		}
	}

    //发布问题回答
	private void publishAnswer(String content) {
		mPublishAnswerBtn.setProgress(50);
        //创建一个发布问题回答的网络请求
		Downloader.getInstance(this).addAnswer(mQuestionId, content, 1, false, this);
	}

	@Override
    //网络请求响应失败时的操作
	public void onFail(DownloadParams.PARSING_TYPE type, VolleyError error) {
		super.onFail(type, error);
		if (TextUtils.isEmpty(msg)) {
			toast(msg);
		} else {
			toast(R.string.add_answer_fail);
		}
		mPublishAnswerBtn.setProgress(0);
	}

	@Override
    //网络请求响应成功时的操作
	public <T> void onSuccess(DownloadParams.PARSING_TYPE type, T response, Object obj) {
		super.onSuccess(type, response, obj);
		toast(msg);
		mPublishAnswerBtn.setProgress(100);
		setResult(RESULT_OK);
		finish();
	}
}
